/**
 *  在线支付模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	
	require("../../custom/base/component-core.js");
		
	require("../../custom/base/component-md5.js");
	
	var validate = require("../../custom/base/component-validate.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
		
	var async = require("../../custom/base/component-async.js");
	
	
	
	
		
	//初始化函数
	exports.init=function(m){
		
		window.$ldh_pay=m;
		
		base.setFromPage("common");
		
	};
	
	var price=$("#payAmount").text();
	
	//支付时查看我的优惠券使用优惠券支付接口,支付时查看我的账户可支付余额使用余额支付接口
	exports.getAccountInfo=function(){
		
		var params = {
			
		};
		
		eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopweb/Account/getAccountInfo.do", params));
						
				
						if(data["code"]==1){
							
							if(!validate.isNull(data["balance"])){
								
								$("#ldh-yuepay").show();
								
								$("#balance").html(data["balance"]);
								
								exports.setTotalBalance(data["balance"]);
								
								//$("#balance").html("200.251");
								
								//exports.setTotalBalance("200.251");
							}
							
							if(data["coupons"].length>0){
								
								$("#ldh-redpackets").show();
								
								for(var i=0;i<data["coupons"].length;i++){
									
									if(i==0){
										
										$("#text_red_packages_balance").html(data["coupons"][i]["amount"]);
										
										this.couponId=data["coupons"][i]["couponId"];
										
										this.amount=data["coupons"][i]["amount"];
										
									}
									
									$("#couponsList").append('<li><a href=javascript:$ldh_pay.setCouponId("'+data["coupons"][i]["couponId"]+'","'+data["coupons"][i]["amount"]+'")>'+data["coupons"][i]["amount"]+'</a></li>');
									
								}
							}
								
 
						}else{
							
							alert(data["message"]);
							
						}
						
						
						
		}))().start();
		
	};
	
	//勾选余额支付
	exports.setBalancePay=function(obj){
		
		
		
		if ($(obj).hasClass("checked")) {
			$(obj).removeClass("checked");
			$(obj).children().attr("checked", false);
			$("#span_balance_pay").hide();
			$(".ldh-pay-pwd").hide();
			$("#input_pay_password").val("");
			
			exports.calculateAmount(0,"0");
			
		} else {
			
			if($("#ldh-redpackets .ldh-checkbox-span").hasClass("checked") && Number(exports.getRedAmount())>=Number(price)){
				
				alert("红包够支付了");
				return;
			}
			
			$(obj).addClass("checked");
			$(obj).children().attr("checked", true);
			$("#span_balance_pay").show();
			$(".ldh-pay-pwd").show();
			
		}	
		
		$("#input_balance").val("");
		
	};
	
	//勾选使用红包
	exports.setRedPackets=function(obj){
		
		if($("#ldh-yuepay .ldh-checkbox-span").hasClass("checked") && validate.isNull($("#input_balance").val())){
			
			return;
		}
		
		if ($(obj).hasClass("checked")) {
			$(obj).removeClass("checked");
			$(obj).children().attr("checked", false);
			$("#div_redpackage").hide();
			this.amount="";
			exports.calculateAmount(1,"");
		} else {
			
			//判断是否勾选了余额支付并且余额是否够支付,如果满足,则提示
			if(Number($("#input_balance").val())>=Number(price)){
				alert("余额已经够支付了");
				return;
			}
			this.amount=$("#text_red_packages_balance").text();
			exports.calculateAmount(1,$("#text_red_packages_balance").text());
			$(obj).addClass("checked");
			$(obj).children().attr("checked", true);
			$("#div_redpackage").show();
		}	
	};
	
	//设置总余额
	exports.setTotalBalance=function(totalBalance){
		
		this.totalBalance=totalBalance;
		
	};
	
	//获取总余额
	exports.getTotalBalance=function(){
		
		return this.totalBalance==null?"0":this.totalBalance;
		
	};
	
	
	
	//设置红包余额
	exports.setCouponId=function(couponId,amount){
		
		this.couponId=couponId;
		
		this.amount=amount;
		
		$("#text_red_packages_balance").html(amount);
		
		$(".btn-group").removeClass("open");		
		
		exports.calculateAmount(1,amount);
		
	};
	
	//获取余额ID
	exports.getCouponId=function(){
		
		return this.couponId==null?"":this.couponId;
		
	};
	
	//获取选择的红包余额
	exports.getRedAmount=function(){
		
		return this.amount==null?"0":this.amount;
		
	};
	
	

	//Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
	var newStr="",oldStr="";
	exports.OnInput=function(event) {
		
		newStr=event.target.value;

	
		exports.OnChangeInput();
		
	};
	
	//监听input
	exports.OnChangeInput=function(){
		
		
		if(Number(newStr)>Number(price)){
			
	    	$("#input_balance").val(oldStr);
	    	
			return;
			
		}	
	
		if(!validate.isNull(newStr)){
			
			//判断第一个字符是不是.号
			if(newStr.substring(0, 1)=="."){
				
				 $("#input_balance").val(oldStr);
				 				 
				 return;
				 
			}else{
			
				//判断有没有小数点
				if(newStr.indexOf(".")>=0){
					
					var array=newStr.split(".");
					//判断字符串不能存在两个或以上的.号
					if(array.length>2){
						
						$("#input_balance").val(oldStr);
						 					
						return;
						
					}else{
						
						//当小数点后面是否为空
						if(validate.isNull(array[1])){
							
							
							//判断是否按BackSpace删除的
						/*	if(newStr.length>oldStr.length){
								$("#input_balance").val(newStr+"0");
								
							}else{
								
								$("#input_balance").val(newStr.substring(0, newStr.length-1));
							}*/
							newStr=newStr.substring(0,newStr.length-1);
							
							
						}
						
						//判断小数点后面的数是不是数字
					    if(!validate.isNull(array[1]) && !validate.isNumber(array[1]))	{
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }
					    
					    //小数点后面是否大于三位数字
					    if(array[1].length>3)	{
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }
					    
					    //判断当前输入的数字是否大于余额
					    if(Number(newStr)>Number(exports.getTotalBalance())){
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }else{
					    	
					    	exports.calculateAmount(0,newStr);
					    }
					   
						
						oldStr=newStr;
						
					}
					
					
				}else{
					
					//判断小数点后面的数是不是数字
				    if(!validate.isNumber(newStr))	{
				    	
				    	$("#input_balance").val(oldStr);
				    	
				    	return;
				    }
				    
				    //判断当前输入的数字是否大于余额
				    if(Number(newStr)>Number(exports.getTotalBalance())){
				    	
				    	$("#input_balance").val(oldStr);
				    	
				    	return;
				    }else{
				    	
				    	exports.calculateAmount(0,newStr);
				    	
				    	
				    }
				    
				    oldStr=newStr;
				   
					
				}
				
				
			}
			
		}else{
			
			exports.calculateAmount(0,newStr);
			
			 oldStr=newStr;
		}
		
		
		
	};
	
	// Internet Explorer
	exports.OnPropChanged=function(event) {
	    if (event.propertyName.toLowerCase () == "value") {
	    	
	        newStr=event.srcElement.value;

			exports.OnChangeInput();
	    }
	};
	
	
	exports.calculateAmount=function(type,newStr){
		
		if(type==0){

			
			var redAmount=0;
			if($("#ldh-redpackets .ldh-checkbox-span").hasClass("checked")){
				redAmount=Number(exports.getRedAmount());
			}
			
			$("#balance").text((Number(exports.getTotalBalance())-Number(newStr)).toFixed(3));
			
			if(Number(price)-Number(newStr).toFixed(2)-redAmount<0){
				
				$("#online_pay_amount").text("0");

			}else{
				
				$("#online_pay_amount").text((Number(price)-Number(newStr)-redAmount).toFixed(2));

			}
			
			
		}else{
			
			var input_balance=$("#input_balance").val();
			
			if(!validate.isNull(input_balance)){
				
				input_balance=Number(input_balance);
			}else{
				input_balance=0;
			}
			
			if(Number(price)-input_balance<=Number(exports.getRedAmount())){
				
				$("#online_pay_amount").text("0");
				
			}else{
				
				$("#online_pay_amount").text((Number(price)-input_balance-Number(exports.getRedAmount())).toFixed(2));

			}
		}
		
	
	};
	
	
	
	exports.goAliPay=function(){
		
		base.showLoading();
		
		var orderId=base.getParameter("orderId");
		
		var orderAmount=base.getParameter("orderAmount");
		
		var params = {
				"userId":$ldh_base.getCookie("userId"),
				"order":orderId,
				"orderAmount":orderAmount,
				"payType":"08"
		};
		
		eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopweb/Transaction/reconstructParams.do", params));
						
						
						if(data.code=="1"){
							
							//如果返回有值,表示红包或者余额支付还不够，需要在线支付
							if(!validate.isNull(data["paramValue"])){
								
								//_AP.pay("https://mclient.alipay.com/service/rest.htm?call_back_url=http%3A%2F%2Fm.taobao.com&partner=2088201962473581&sec_id=MD5&v=2.0&format=xml&req_data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22%3F%3E%3Cauth_and_execute_req%3E%3Crequest_token%3E201502045307e4beed899e2d08ee2d5b24745c80%3C%2Frequest_token%3E%3C%2Fauth_and_execute_req%3E&sign=1eee4b7f34c3ea185c084d6b723b7843&service=alipay.wap.auth.authAndExecute");
								
								

															// {"paramValue":"<form
															// id=\"ddf_web_payForm\"
															// name=\"ddf_web_payForm\"
															// action=\"http://wappaygw.alipay.com/service/rest.htm?_input_charset=utf-8\"
															// method=\"get\"><input
															// type=\"hidden\"
															// name=\"sign\"
															// value=\"vd76RYj4Se84pp0RwHo9A6kP5dekHuNy43CX6VzY2ND5rS9n+TFwgXAcTTvjWuhGxJF92/I4S3YBXYaLTZKDs4eUYrQD5ZdmH7vlFts3DSe+oPtZx/RtRx+qb1HXaa/m0IBjfXQ9voWLs926QayIOIXDXPA+f+diuP4C9H7RF/g=\"/><input
															// type=\"hidden\"
															// name=\"sec_id\"
															// value=\"0001\"/><input
															// type=\"hidden\"
															// name=\"v\"
															// value=\"2.0\"/><input
															// type=\"hidden\"
															// name=\"_input_charset\"
															// value=\"utf-8\"/><input
															// type=\"hidden\"
															// name=\"req_data\"
															// value=\"<auth_and_execute_req><request_token>201504152f9dbee24409ab5e4d2db1e1fcb4c794<\/request_token><\/auth_and_execute_req>\"/><input
															// type=\"hidden\"
															// name=\"service\"
															// value=\"alipay.wap.auth.authAndExecute\"/><input
															// type=\"hidden\"
															// name=\"partner\"
															// value=\"2088801507051430\"/><input
															// type=\"hidden\"
															// name=\"format\"
															// value=\"xml\"/><input
															// type=\"submit\"
															// value=\"确认\"
															// style=\"display:none;\"><\/form>","code":"1","message":"调用成功"}

								var str='';
								str+=''+data["paramValue"];
							    $("body").append(str);
							    
							    var sign=encodeURIComponent($("#ddf_web_payForm input[name='sign']").val());
							    var sec_id=$("#ddf_web_payForm input[name='sec_id']").val();
							    var v=$("#ddf_web_payForm input[name='v']").val();
							    var req_data=$("#ddf_web_payForm input[name='req_data']").val();
							    var service=$("#ddf_web_payForm input[name='service']").val();
							    var partner=$("#ddf_web_payForm input[name='partner']").val();
							    var format=$("#ddf_web_payForm input[name='format']").val();
							    var url=$("#ddf_web_payForm").attr("action")+"&sign="+sign+"&sec_id="+sec_id+"&v="+v+"&req_data="+req_data+"&service="+service+"&partner="+partner+"&format="+format;
							    
							   // $("body").append(url);
								_AP.pay(url);
								
								
							    //$("#ddf_web_payForm").attr('target', '_blank');
							   // $("#ddf_web_payForm").submit(); 
							}

						}else{
							
						}
						
						base.cancelLoading();
				
		}))().start();
		
	};
	
	//微信授权
	exports.goWxPayOauth=function(){
		
		
	    var orderId=base.getParameter("orderId");
			
		var orderAmount=base.getParameter("orderAmount");
		
		var url=window.location.href;
		
		if(url.indexOf("storeme.cn")>=0){
			
			window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx04391f20ebe12591&redirect_uri=http://www.storeme.cn/mall/v1/h5/pages/oauth_success.jsp&response_type=code&scope=snsapi_base&state='+orderId+','+orderAmount+'&connect_redirect=1#wechat_redirect';

		}else if(url.indexOf("jujie.xyz")>=0){
			
			window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx04391f20ebe12591&redirect_uri=http://www.jujie.xyz/mall/v1/h5/pages/oauth_success.jsp&response_type=code&scope=snsapi_base&state='+orderId+','+orderAmount+'&connect_redirect=1#wechat_redirect';

		}else{
			
			showTips("该授权域名无效");
		}
		
		
	};
	
	
	
	 //微信支付
	   exports.goWxPay=function(code,url,orderId,orderAmount){
		//alert("code:"+code+"***"+"url:"+url+"***"+"orderId:"+orderId+"***"+"orderAmount:"+orderAmount);
		   base.showLoading();
		   
			var params = {
					"code":code,
					"url":url,
					"tradeType":"JSAPI",
					"userId":$ldh_base.getCookie("userId"),
					"orderAmount":orderAmount,
					"orderId":orderId,
					"channelCode":"01"
			};
			
			eval(
						Wind.compile("async", function() {
							
							var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopapp/WebPay/payByWXPay.do", params));
							
							if(data.code=="1"){
								

								 // 加载一个模块
								  require.async(['http://res.wx.qq.com/open/js/jweixin-1.0.0.js'], function(wx,b) {
									  
									  //var url=location.href.split('#')[0];
									  //alert(CryptoJS.SHA1("jsapi_ticket="+data["ticket"]+"&noncestr="+data["noncestr"]+"&timestamp="+data["timestamp"]+"&url="+url));
									 /* $("#appid").val(data["appid"]);
									  $("#timestamp").val(data["timestamp"]);
									  $("#noncestr").val(data["noncestr"]);
									  $("#url").val(wx_pay_url);
									  $("#signature").val(CryptoJS.SHA1("jsapi_ticket="+data["ticket"]+"&noncestr="+data["noncestr"]+"&timestamp="+data["timestamp"]+"&url="+wx_pay_url));
									  $("#signature_server").val(data["signature"]);*/

								    wx.config({
									      debug:false,
									      appId: data["appid"],
									      timestamp: data["timestamp"],
									      nonceStr: data["noncestr"],
									      signature:data["config_signature"],
									      jsApiList: [
									                  'checkJsApi',
									                  'onMenuShareTimeline',
									                  'onMenuShareAppMessage',
									                  'onMenuShareQQ',
									                  'onMenuShareWeibo',
									                  'chooseWXPay'
									      ]
									  });
									
									  
									   wx.ready(function () {
										   
										 var packages=data["package"];
										   wx.chooseWXPay({
										       timestamp: data["timestamp"],
										       nonceStr: data["noncestr"],
										       package:packages,
										       signType: "MD5", // 注意：新版支付接口使用 MD5 加密
										       paySign:data["sign"],
										       success: function (res) {
										           // 支付成功后的回调函数
										    	  //alert("支付成功");$ldh_base.getCookie("loginSign")
										    	   
										    	   var loginSign=$ldh_base.getCookie("loginSign");
										    	   
										    	   var userId=$ldh_base.getCookie("userId");
										    	   
										    	   window.location.href=ctx+"/v1/h5/pages/pay_success/"+userId+"/"+loginSign+".html";
										    	   
										    	  
										       }
										     });
									  });  
									  
									   wx.error(function (res) {
									 	  
									 	 if(res.errMsg=="chooseWXPay:cancel"){
									 											
									 		alert("你已取消支付");
									 		window.location.href=ctx+"/v1/h5/pages/index.jsp";
									 	 }else{
									 		 									 		 
									 		//alert(res.errMsg);
											
									 	 }
									 	
									 	});
								  });
								
								

							}else{
								
							}
							
							base.cancelLoading();
			}))().start();
			
		};
	 

	//定时提示信息
	var tips_task = eval(Wind.compile("async", function (divId) {
		
	    $await(Wind.Async.sleep(2000));
	   
	    $(divId).html("");
	    
	}));
	
	var task = eval(Wind.compile("async", function (divId) {
	    $await(tips_task(divId));
	}));
	
});

